export default {
	data() {
		return {
			enterTime: '',
			mdLeaveTime: '',
			pnames: {
				'pages/welcome': '欢迎',
				'pages/index/index': '首页',
				'pages/touristMap/index': '导览',
				'pages/oneCodePass/index': '一码通',
				'': '商城',
				'pages/my/index': '我的'
			},
			pageTitle: ''
		}
	},
	onShow() {
		this.enterTime = new Date().Format('yyyy-MM-dd hh:mm:ss');
		this.pageTitle = (this.$children&&this.$children[0])?this.$children[0].title:'';
	},
	onHide() {
		this.mdLeaveTime = new Date().Format('yyyy-MM-dd hh:mm:ss');
		this.setHistory();
	},
	onUnLoad() {
		this.mdLeaveTime = new Date().Format('yyyy-MM-dd hh:mm:ss');
		this.setHistory();
	},
	destroyed() {
		this.mdLeaveTime = new Date().Format('yyyy-MM-dd hh:mm:ss');
		this.setHistory();
	},
	methods: {
		setHistory() {
			if (!uni.getStorageSync('userInfo')) return
			if (this.mdLeaveTime && this.enterTime) {
				let diff = Date.parse(this.mdLeaveTime) - Date.parse(this.enterTime);
				let ds = Math.ceil(diff / 1000); //秒
				let pages = getCurrentPages(); //获取页面栈
				let lastPage = pages[pages.length - 1]; //获取最后一个页面
				let route = lastPage.route; //获取最后一个页面的路由
				let title = lastPage.$vm.$scope.data.titleHeader || lastPage.$vm.$scope.data.title; //获取页面标题
				let keys = Object.keys(this.pnames);
				let t = keys.find(k => k == route);
				// if (t) title = this.pnames[t];
				if (t) return //不记录一级菜单
				let options = lastPage.$vm.$mp.page.options; //获取页面参数
				let lastRoute = ''; //获取上一个页面路由
				if (pages.length > 1) {
					lastRoute = pages[pages.length - 2].route;
				}

				let params = {
					createDate: this.enterTime, //创建时间
					eventType: '3', //事件类型
					mdmTime: this.enterTime, //埋点时间
					openId: JSON.parse(uni.getStorageSync('userInfo')).openId, //小程序用户
					pvName: this.pageTitle || title, //页面名称
					pvPath: route, //页面路径
					pvReferer: lastRoute, //引用页面地址
					pvQuery: JSON.stringify(options) == "{}" ? '' : JSON.stringify(options), //页面参数
					pvTime: ds //	访问时长
				};
				this.toSend(params);
			}
		},
		toSend(params) {
			let dto = {
				...params,
				appId: 'wxe6afb089695f90e7',
				cookieId: this.generateCookieId(), //用户识别ID
				ipAddress: uni.getStorageSync('userIp'), //IP地址
				sessionId: JSON.parse(uni.getStorageSync('userInfo')).openId, //用户会话ID
				// userAgent:JSON.stringify(uni.getSystemInfoSync())
				userAgent: ''
			}
			this.$api.post('/api/mdmbs/insertPv', dto).then(res => {
				if (res.data.code === 0) {

				}
			})
		},
		generateCookieId() {
			const cookieId = 'cookieId_' + Math.random().toString(36).substr(2, 9);
			return cookieId;
		}
	}
}